<template>
  <div class="distribution-container">
    <div class="header">
      <title-view title="分配人员" />
      <el-button @click="handelBack">返回</el-button>
    </div>
    <div class="content">
      <div class="content-roles" v-loading="isLoadingRole">
        <div class="content-roles__items">
          <template v-if="rolesList.length">
            <div class="content-roles-item" v-for="item in rolesList" :key="item.roleId">
              <div class="content-roles-item-title">
                <span>{{ item.roleName }}</span>
                <el-button type="primary" link @click="handelUpdateUser(item)" v-if="item.isAuth && item.userId"
                  >重新分配</el-button
                >
              </div>
              <div class="content-roles-item-title" style="color: red" v-show="item.dispenseMark">任务即将开始，需分配</div>
              <div
                class="content-roles-item-user"
                :class="{ 'active-user': item.roleId === userForm.roleId }"
                @click.stop="handelSetTask(item)"
                v-if="item.userId"
              >
                <div class="user-avatar">
                  <AvatarView :info="item" avatarName="userName" :avatarStyle="avatarStyle" />
                </div>
                <div class="user-info">
                  <div class="user-info-name">{{ item.userName }} {{ item.mobile }}</div>
                  <div class="user-info-role">{{ item.deptName }}</div>
                </div>
                <!-- 删除选择 start-->
                <div class="user-del" @click="handelDelUser(item)">
                  <el-button link :icon="CircleCloseFilled"></el-button>
                </div>
                <!-- 删除选择 end -->
              </div>
              <div class="content-roles-item-disable" v-if="!item.isAuth && !item.userId">无权限添加</div>
              <div class="content-roles-item-add" @click="handelAddUser(item)" v-if="item.isAuth && !item.userId">
                <el-icon><Plus /></el-icon>
                添加人员
              </div>
            </div>
          </template>
          <el-empty v-else />
        </div>
        <el-button class="content-roles__button" type="primary" :icon="Plus" @click="handelAddRole">新增角色</el-button>
      </div>
      <div class="content-tasks">
        <div class="content-tasks-title">任务设置</div>
        <div class="content-tasks-list" v-loading="isLoadingTask">
          <template v-if="taskList.length">
            <div class="content-tasks-list-item" v-for="item in taskList" :key="item.taskId">
              <div class="list-item-options">
                <div class="list-item-options-icon"></div>
                <div class="list-item-options-type" v-show="[2, 3].includes(item.taskNodeType)">【整改】</div>
                <div class="list-item-options-type" v-show="[5].includes(item.taskNodeType)">【增减项】</div>
                <div class="list-item-options-label">{{ item.taskName }}</div>
                <el-button type="primary" link @click="handelOptionInfo(item)">操作说明</el-button>
              </div>
              <div class="list-item-info">
                <div class="list-item-info-item"><span>人员：</span>{{ item.userName }}</div>
                <div class="list-item-info-item">
                  <span>任务开始时间：</span>
                  <span v-if="item.originalPlainStartDate">{{ item.originalPlainStartDate }}</span>
                  <template v-if="item.status === 1">
                    <el-button type="primary" link @click="handelSetTime(item)" v-if="!item.originalPlainStartDate">
                      设置
                      <el-icon><Edit /></el-icon>
                    </el-button>
                    <el-button type="primary" link @click="handelUpdateTime(item)" v-else>
                      修改
                      <el-icon><Edit /></el-icon>
                    </el-button>
                  </template>
                </div>
              </div>
            </div>
          </template>
          <el-empty description="暂时什么都没有，请先分配人员" v-else>
            <template #image>
              <svg-icon iconClass="empty-data" />
            </template>
          </el-empty>
        </div>
      </div>
    </div>

    <!--  选择人员  -->
    <el-dialog v-model="isShowUser" width="474" :align-center="true" :show-close="false" :close-on-click-modal="false">
      <template #header>
        <title-view title="添加人员"></title-view>
      </template>
      <el-form ref="userFormRef" :model="userForm" label-width="80px" status-icon v-loading="isLoadingUser">
        <el-form-item label="员工姓名" prop="userId" :rules="[{ required: true, message: '请选择人员', trigger: 'change' }]">
          <el-select v-model="userForm.userId" filterable placeholder="请输入关键字或选择" @change="changeUser">
            <el-option v-for="item in userData" :key="item.userId" :label="item.nickName" :value="item.userId" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button style="width: 92px; background-color: #f2f3f5" @click="handelUserClose" size="large">取消</el-button>
          <el-button style="width: 92px" type="primary" @click="handelUserSubmit" size="large" :disabled="isLoadingUser"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>

    <!--  设置时间  -->
    <el-dialog v-model="isShowSetTime" width="474" :align-center="true" :show-close="false" :close-on-click-modal="false">
      <template #header>
        <title-view title="设置时间"></title-view>
      </template>
      <el-form ref="timeFormRef" :model="taskTimeForm" label-width="120px" status-icon v-loading="isLoadingTime">
        <el-form-item
          label="任务开始时间"
          prop="originalPlainStartDate"
          :rules="[{ required: true, message: '请选择时间', trigger: 'change' }]"
        >
          <el-date-picker
            style="width: 100%"
            v-model="taskTimeForm.originalPlainStartDate"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            type="date"
            size="default"
            clearable
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button style="width: 92px; background-color: #f2f3f5" @click="handelTimeClose" size="large">取消</el-button>
          <el-button style="width: 92px" type="primary" @click="handelTimeSubmit" :loading="isLoadingTime" size="large"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>

    <!--  操作说明  -->
    <el-dialog v-model="isShowOperateRemark" width="50vw" :align-center="true" @close="handelCloseOption">
      <template #header>
        <title-view title="操作说明"></title-view>
      </template>
      <div class="pd20 operate-remark">
        <div v-if="operateRemark" v-html="operateRemark"></div>
        <el-empty v-else />
      </div>
    </el-dialog>

    <!--  新增角色   -->
    <multiple-allocation
      v-if="showMultipleAllocation"
      v-model="showMultipleAllocation"
      @multipleAllocationSave="multipleAllocationSave"
      :selectCustomersArr="selectCustomersArr"
    ></multiple-allocation>
  </div>
</template>

<script setup>
import { nextTick, ref, getCurrentInstance } from "vue";
import { Edit, Plus, CircleCloseFilled } from "@element-plus/icons-vue";
import { dayjs } from "element-plus";
import { useRouteQuery } from "@vueuse/router";
import { useRouter } from "vue-router";
import AvatarView from "@/components/AvatarView";
import MultipleAllocation from "./components/MultipleAllocation";
import * as requestApi from "@/apis/allocation";
import { clientAssign } from "@/apis/clientManager";

const router = useRouter();
const { proxy } = getCurrentInstance();
const avatarStyle = {
  width: "50px",
  height: "50px",
  borderRadius: "50%"
};

const customerId = useRouteQuery("customerId");
const reformType = useRouteQuery("reformType");
const stageType = useRouteQuery("stageType");
const backPageUrl = useRouteQuery("backPageUrl");
const backUrl = ref("");
backPageUrl.value && (backUrl.value = backPageUrl.value);

const rolesList = ref([]);
const isShowUser = ref(false);
const isLoadingRole = ref(false);
const isLoadingUser = ref(false);
const userData = ref([]);
const initUserForm = {
  roleId: "",
  deptId: "",
  deptName: "",
  userId: "",
  userName: "",
  type: 1,
  customerIds: [customerId.value]
};
const userForm = ref({ ...initUserForm });
const getRoleList = async () => {
  try {
    isLoadingRole.value = true;
    const { data } = await requestApi.roleList(customerId.value, reformType.value, stageType.value);
    rolesList.value = data ?? [];
    isLoadingRole.value = false;
  } catch (err) {
    isLoadingRole.value = false;
  }
};
const getUserData = async () => {
  try {
    isLoadingUser.value = true;
    const params = {
      roleId: userForm.value.roleId,
      searchValue: ""
    };
    const { data } = await requestApi.memberList(params);
    userData.value = data ?? [];
    isLoadingUser.value = false;
  } catch (err) {
    isLoadingUser.value = false;
  }
};
const changeUser = val => {
  const selectData = userData.value.find(item => item.userId === val);
  userForm.value.userName = selectData?.nickName || "";
  userForm.value.deptName = selectData?.deptName || "";
  userForm.value.deptId = selectData?.deptId || "";
};
const handelAddUser = data => {
  userForm.value = { ...initUserForm, ...data };
  getUserData();
  isShowUser.value = true;
};
const handelUpdateUser = data => {
  userForm.value = { ...initUserForm, ...data };
  getUserData();
  isShowUser.value = true;
};
const handelUserSubmit = () => {
  proxy.$refs.userFormRef.validate(async val => {
    if (!val) {
      return proxy.$modal.msgError("请填写完整信息");
    }
    try {
      isLoadingUser.value = true;
      await clientAssign(userForm.value);
      proxy.$modal.msgSuccess("设置成功");
      isLoadingUser.value = false;
      taskList.value = [];
      getRoleList();
      handelUserClose();
    } catch (err) {
      isLoadingUser.value = false;
    }
  });
};
const handelUserClose = async () => {
  await nextTick();
  proxy.$refs.userFormRef.resetFields();
  userForm.value = { ...initUserForm };
  isShowUser.value = false;
};

const taskList = ref([]);
const isLoadingTask = ref(false);
const getBeforeTaskListByRoleId = async roleId => {
  try {
    isLoadingTask.value = true;
    const { data } = await requestApi.beforeTaskListByRoleId(roleId, customerId.value, reformType.value);
    taskList.value = data ?? [];
    isLoadingTask.value = false;
  } catch (err) {
    isLoadingTask.value = false;
  }
};
const handelSetTask = data => {
  if (!data.isAuth) {
    return (taskList.value = []);
  }
  userForm.value = { ...initUserForm, ...data };
  getBeforeTaskListByRoleId(data.roleId);
};

/**
 * 删除分配
 */
const handelDelUser = async data => {
  proxy.$modal.confirm("是否删除该角色负责人？").then(async () => {
    try {
      isLoadingTime.value = true;
      await requestApi.removeAssign(customerId.value, data.userId, data.roleId);
      proxy.$modal.msgSuccess("删除成功");
      isLoadingTime.value = false;
      taskList.value = [];
      getRoleList();
    } catch (err) {}
  });
};

const isShowSetTime = ref(false);
const isLoadingTime = ref(false);
const taskTimeForm = ref({
  stageTaskId: "",
  customerId: "",
  originalPlainStartDate: dayjs().format("YYYY-MM-DD")
});
const handelSetTime = data => {
  taskTimeForm.value.stageTaskId = data.stageTaskId;
  taskTimeForm.value.customerId = customerId.value;
  isShowSetTime.value = true;
};
const handelUpdateTime = data => {
  taskTimeForm.value.stageTaskId = data.stageTaskId;
  taskTimeForm.value.originalPlainStartDate = data.originalPlainStartDate;
  taskTimeForm.value.customerId = customerId.value;
  isShowSetTime.value = true;
};
const handelTimeClose = async () => {
  await nextTick();
  proxy.$refs.timeFormRef.resetFields();
  taskTimeForm.value = {
    stageTaskId: userForm.value.stageTaskId,
    customerId: customerId.value,
    originalPlainStartDate: dayjs().format("YYYY-MM-DD")
  };
  isShowSetTime.value = false;
};
const handelTimeSubmit = () => {
  proxy.$refs.timeFormRef.validate(async val => {
    if (!val) {
      return proxy.$modal.msgError("请填写完整信息");
    }
    try {
      isLoadingTime.value = true;
      await requestApi.setStartTime(taskTimeForm.value);
      proxy.$modal.msgSuccess("设置成功");
      isLoadingTime.value = false;
      getBeforeTaskListByRoleId(userForm.value.roleId);
      handelTimeClose();
    } catch (err) {
      isLoadingTime.value = false;
    }
  });
};

/**
 * 返回
 */
const handelBack = () => {
  const baseRouter = window.microApp.router.getBaseAppRouter();
  if (backUrl.value) {
    return baseRouter.push({ path: backUrl.value });
  }
  router.go(-1);
};

const isShowOperateRemark = ref(false);
const operateRemark = ref("");
const handelOptionInfo = data => {
  operateRemark.value = data.operateRemark;
  // operateRemark.value =
  //   '<h2 style="text-align: right;"><s>操作说明</s></h2><p><img src="http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/PROCESS/iShot_2023-05-09_14.37.17_%E5%89%AF%E6%9C%AC-2024-07-18%2014%3A34%3A37.avif" alt="" data-href="http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/PROCESS/iShot_2023-05-09_14.37.17_%E5%89%AF%E6%9C%AC-2024-07-18%2014%3A34%3A37.avif" style="width: 356.00px;height: 264.59px;"/></p><h1 style="text-align: center;"><span style="color: rgb(231, 95, 51);">操作说明</span></h1><p><img src="http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/PROCESS/wallhaven-1ke773-2024-07-18%2014%3A34%3A53.jpeg" alt="" data-href="http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/PROCESS/wallhaven-1ke773-2024-07-18%2014%3A34%3A53.jpeg" style=""/></p>';
  isShowOperateRemark.value = true;
};
const handelCloseOption = () => {
  isShowOperateRemark.value = false;
  operateRemark.value = "";
};

const showMultipleAllocation = ref(false);
const selectCustomersArr = ref([customerId.value]);
const handelAddRole = () => {
  showMultipleAllocation.value = true;
};
const multipleAllocationSave = data => {
  // console.log(data, "<<<<<");
  getRoleList();
};

getRoleList();
</script>

<style scoped lang="scss">
@use "distribution";
</style>
